<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件上传与留言板系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
            line-height: 1.6;
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        .container {
            display: flex;
            gap: 20px;
        }
        .section {
            flex: 1;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 20px;
            background-color: #f9f9f9;
        }
        .section-title {
            margin-top: 0;
            color: #444;
            border-bottom: 1px solid #ddd;
            padding-bottom: 10px;
        }
        
        /* 文件上传部分样式 */
        .upload-container {
            border: 2px dashed #ccc;
            border-radius: 5px;
            padding: 20px;
            text-align: center;
            margin: 15px 0;
        }
        .upload-container:hover {
            border-color: #999;
        }
        #file-input {
            display: none;
        }
        .upload-btn {
            background-color: #4CAF50;
            color: white;
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .upload-btn:hover {
            background-color: #45a049;
        }
        #file-info {
            margin-top: 10px;
            font-size: 14px;
        }
        #submit-btn {
            background-color: #2196F3;
            color: white;
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            display: block;
            margin: 15px auto;
        }
        #submit-btn:hover {
            background-color: #0b7dda;
        }
        #submit-btn:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        
        /* 留言板部分样式 */
        #message-form {
            margin-top: 20px;
        }
        #message-input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            resize: vertical;
            min-height: 80px;
            margin-bottom: 10px;
        }
        #submit-message {
            background-color: #ff9800;
            color: white;
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        #submit-message:hover {
            background-color: #e68a00;
        }
        #messages-container {
            margin-top: 20px;
            max-height: 400px;
            overflow-y: auto;
        }
        .message {
            background-color: white;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 12px;
            margin-bottom: 10px;
            position: relative;
        }
        .message-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-size: 14px;
        }
        .message-author {
            font-weight: bold;
            color: #2196F3;
        }
        .message-time {
            color: #777;
            font-size: 12px;
        }
        .message-content {
            word-wrap: break-word;
        }
        
        /* 进度条和通知样式 */
        .progress-container {
            width: 100%;
            background-color: #ddd;
            border-radius: 5px;
            margin: 15px 0;
            display: none;
        }
        #progress-bar {
            width: 0%;
            height: 20px;
            background-color: #4CAF50;
            border-radius: 5px;
            text-align: center;
            line-height: 20px;
            color: white;
            font-size: 12px;
        }
        .notification {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            display: none;
        }
        .success {
            background-color: #dff0d8;
            color: #3c763d;
            border: 1px solid #d6e9c6;
        }
        .error {
            background-color: #f2dede;
            color: #a94442;
            border: 1px solid #ebccd1;
        }
.delete-btn {
    background-color: #f44336;
    color: white;
    border: none;
    border-radius: 3px;
    padding: 3px 8px;
    font-size: 12px;
    cursor: pointer;
    float: right;
    margin-top: -25px;
}

.delete-btn:hover {
    background-color: #d32f2f;
}
    </style>
</head>
<body>
    <h1>文件上传与留言板系统</h1>
    
    <div class="container">
        <!-- 文件上传部分 -->
        <div class="section">
            <h2 class="section-title">文件上传</h2>
            
            <form id="upload-form" action="/upload" method="post" enctype="multipart/form-data">
                <div class="upload-container">
                    <label for="file-input">
                        <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="#ccc" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                            <polyline points="17 8 12 3 7 8"></polyline>
                            <line x1="12" y1="3" x2="12" y2="15"></line>
                        </svg>
                        <p>点击或拖拽文件到此处上传</p>
                        <button type="button" class="upload-btn">选择文件</button>
                        <input type="file" id="file-input" name="file" multiple>
                    </label>
                    <div id="file-info"></div>
                </div>
                
                <div class="progress-container" id="progress-container">
                    <div id="progress-bar">0%</div>
                </div>
                
                <button type="submit" id="submit-btn" disabled>上传文件</button>
            </form>
            
            <div id="upload-notification" class="notification"></div>
        </div>
        
        <!-- 留言板部分 -->
        <div class="section">
            <h2 class="section-title">留言板</h2>
            
            <form id="message-form">
                <textarea id="message-input" placeholder="请输入您的留言..." required></textarea>
                <button type="submit" id="submit-message">发布留言</button>
            </form>
            
            <div id="messages-container"></div>
            
            <div id="message-notification" class="notification"></div>
        </div>
    </div>

    
    <script>
        // 文件上传功能
        const fileInput = document.getElementById('file-input');
        const fileInfo = document.getElementById('file-info');
        const submitBtn = document.getElementById('submit-btn');
        const uploadForm = document.getElementById('upload-form');
        const progressContainer = document.getElementById('progress-container');
        const progressBar = document.getElementById('progress-bar');
        const uploadNotification = document.getElementById('upload-notification');
        
        // 留言板功能
        const messageForm = document.getElementById('message-form');
        const messageInput = document.getElementById('message-input');
        const messagesContainer = document.getElementById('messages-container');
        const messageNotification = document.getElementById('message-notification');
        
        // 初始化 - 加载现有留言
        document.addEventListener('DOMContentLoaded', loadMessages);
        
        // 文件上传功能
        document.querySelector('.upload-btn').addEventListener('click', function(e) {
            e.preventDefault();
            fileInput.click();
        });
        
        const uploadContainer = document.querySelector('.upload-container');
        
        uploadContainer.addEventListener('dragover', function(e) {
            e.preventDefault();
            this.style.borderColor = '#4CAF50';
        });
        
        uploadContainer.addEventListener('dragleave', function() {
            this.style.borderColor = '#ccc';
        });
        
        uploadContainer.addEventListener('drop', function(e) {
            e.preventDefault();
            this.style.borderColor = '#ccc';
            
            if (e.dataTransfer.files.length) {
                fileInput.files = e.dataTransfer.files;
                updateFileInfo();
            }
        });
        
        fileInput.addEventListener('change', updateFileInfo);
        
        function updateFileInfo() {
            if (fileInput.files.length > 0) {
                let fileNames = [];
                let totalSize = 0;
                
                for (let i = 0; i < fileInput.files.length; i++) {
                    fileNames.push(fileInput.files[i].name);
                    totalSize += fileInput.files[i].size;
                }
                
                const sizeInMB = (totalSize / (1024 * 1024)).toFixed(2);
                
                fileInfo.innerHTML = `
                    <strong>已选择 ${fileInput.files.length} 个文件:</strong><br>
                    ${fileNames.join('<br>')}<br>
                    <strong>总大小:</strong> ${sizeInMB} MB
                `;
                
                submitBtn.disabled = false;
            } else {
                fileInfo.textContent = '';
                submitBtn.disabled = true;
            }
        }
        
        uploadForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const xhr = new XMLHttpRequest();
            
            progressContainer.style.display = 'block';
            uploadNotification.style.display = 'none';
            
            xhr.upload.addEventListener('progress', function(e) {
                if (e.lengthComputable) {
                    const percent = Math.round((e.loaded / e.total) * 100);
                    progressBar.style.width = percent + '%';
                    progressBar.textContent = percent + '%';
                }
            });
            
            xhr.addEventListener('load', function() {
                try {
                    const response = JSON.parse(xhr.responseText);
                    if (xhr.status === 200) {
                        showNotification(uploadNotification, response.message || '文件上传成功!', 'success');
                    } else {
                        showNotification(uploadNotification, response.error || '上传过程中出现错误', 'error');
                    }
                } catch (e) {
                    showNotification(uploadNotification, '文件上传完成，但服务器响应异常', 'error');
                }
                
                setTimeout(() => {
                    progressContainer.style.display = 'none';
                    progressBar.style.width = '0%';
                    progressBar.textContent = '0%';
                    fileInput.value = '';
                    updateFileInfo();
                }, 2000);
            });
            
            xhr.addEventListener('error', function() {
                showNotification(uploadNotification, '上传过程中发生错误', 'error');
                progressContainer.style.display = 'none';
            });
            
            xhr.open('POST', this.action, true);
            xhr.send(formData);
        });
        
        // 留言板功能
        messageForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const message = messageInput.value.trim();
            if (!message) return;
            
            const xhr = new XMLHttpRequest();
            xhr.open('POST', '/message', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            
            xhr.onload = function() {
                if (xhr.status === 200) {
                    messageInput.value = '';
                    loadMessages();
                    showNotification(messageNotification, '留言发布成功!', 'success');
                } else {
                    showNotification(messageNotification, '留言发布失败', 'error');
                }
            };
            
            xhr.onerror = function() {
                showNotification(messageNotification, '网络错误，请重试', 'error');
            };
            
            xhr.send(JSON.stringify({ content: message }));
        });
        
        function loadMessages() {
            const xhr = new XMLHttpRequest();
            xhr.open('GET', '/message', true);
            
            xhr.onload = function() {
                if (xhr.status === 200) {
                    try {
                        const messages = JSON.parse(xhr.responseText);
                        displayMessages(messages);
                    } catch (e) {
                        console.error('解析留言数据失败:', e);
                    }
                }
            };
            
            xhr.send();
        }
        
        function displayMessages(messages) {
            messagesContainer.innerHTML = '';
            
            if (messages.length === 0) {
                messagesContainer.innerHTML = '<p>暂无留言</p>';
                return;
            }
            
            messages.forEach(msg => {
                const messageElement = document.createElement('div');
                messageElement.className = 'message';
                
                const time = new Date(msg.timestamp).toLocaleString();
                
                messageElement.innerHTML = `
                    <div class="message-header">
                        <span class="message-author">${msg.author || '匿名用户'}</span>
                        <span class="message-time">${time}</span>
                    </div>
                    <div class="message-content">${msg.content}</div>
                `;
                
                messagesContainer.appendChild(messageElement);
            });
        }
        
        function showNotification(element, message, type) {
            element.textContent = message;
            element.className = 'notification ' + type;
            element.style.display = 'block';
            
            setTimeout(() => {
                element.style.display = 'none';
            }, 3000);
        }

messageForm.addEventListener('submit', function(e) {
  e.preventDefault();
  const message = messageInput.value.trim();
  if (!message) return;

  fetch('/message', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ content: message })
  })
  .then(response => {
    if (!response.ok) throw new Error('网络响应异常');
    return response.json();
  })
  .then(data => {
    console.log('服务器返回:', data); // 调试日志
    messageInput.value = '';
    loadMessages();
    showNotification(messageNotification, '留言发布成功!', 'success');
  })
  .catch(error => {
    console.error('提交留言失败:', error); // 调试日志
    showNotification(messageNotification, '留言发布失败', 'error');
  });
});


// 加载现有留言
function loadMessages() {
    fetch('/messages')
        .then(response => response.json())
        .then(messages => {
            displayMessages(messages);
        })
        .catch(error => {
            console.error('获取留言失败:', error);
            showNotification(messageNotification, '加载留言失败', 'error');
        });
}

// 显示留言到页面
function displayMessages(messages) {
    const container = document.getElementById('messages-container');
    container.innerHTML = '';

    if (messages.length === 0) {
        container.innerHTML = '<p>暂无留言</p>';
        return;
    }

    messages.forEach(msg => {
        const messageElement = document.createElement('div');
        messageElement.className = 'message';
        messageElement.dataset.id = msg.id; // 存储留言ID
        
        const time = new Date(msg.timestamp).toLocaleString();
        
        messageElement.innerHTML = `
            <div class="message-header">
                <span class="message-author">${msg.author || '匿名用户'}</span>
                <span class="message-time">${time}</span>
            </div>
            <div class="message-content">${msg.content}</div>
            <button class="delete-btn" data-id="${msg.id}">删除</button>
        `;
        container.appendChild(messageElement);
    });

    // 添加删除按钮事件监听
    document.querySelectorAll('.delete-btn').forEach(btn => {
        btn.addEventListener('click', deleteMessage);
    });
}

// 页面加载时获取留言
document.addEventListener('DOMContentLoaded', loadMessages);

// 留言提交后刷新列表
document.getElementById('message-form').addEventListener('submit', function(e) {
    e.preventDefault();
    const content = document.getElementById('message-input').value.trim();
    
    fetch('/message', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ content })
    })
    .then(response => response.json())
    .then(data => {
        document.getElementById('message-input').value = ''; // 清空输入框
        loadMessages(); // 重新加载留言列表
        showNotification(messageNotification, '留言发布成功!', 'success');
    })
    .catch(error => {
        console.error('提交留言失败:', error);
        showNotification(messageNotification, '留言发布失败', 'error');
    });
});

// 删除留言函数
function deleteMessage(event) {
    const messageId = event.target.dataset.id;
    
    if (confirm('确定要删除这条留言吗？')) {
        fetch(`/message/${messageId}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification(messageNotification, '留言已删除', 'success');
                loadMessages(); // 刷新留言列表
            } else {
                showNotification(messageNotification, data.error || '删除失败', 'error');
            }
        })
        .catch(error => {
            console.error('删除留言失败:', error);
            showNotification(messageNotification, '删除留言时出错', 'error');
        });
    }
}
    </script>
</body>
</html>